<?php
/**
 * Lightweight game bootstrap and dispatcher
 *
 * @author Matt Pike
 */
class SiteBootstrap extends Bootstrap{

	public function __construct(){
		require_once("SiteConfig.php");
		require_once("GameConfig.php");
		$this->loadCoreResources();
		$this->dispatchRequest($_REQUEST);
	}

	/**
	 * Load and dispatch request
	 */
	public function dispatchRequest(array $request){
		$isAjax = Request::isAjaxRequest();

		$controller = Request::getWord("c",null,$request);
		$action 	= Request::getWord("a",null,$request);

		try{
			if(!$controller){
				throw new BadRequest("Invalid controller: c=$controller a=$action");
			}

			if($this->loadController($controller) && (!$action || ($action && $this->actionExists($controller,$action)))){
				if($isAjax){
					echo json_encode($this->callAction($controller, $action, $request));
				}else{
					echo $this->callAction($controller, $action, $request);
				}
				exit;
			}else{
				throw new BadRequest("Unrecognised controller: ".$controller);
			}
		}catch(Exception $e){
			throw $e;
		}
		//TEMPORARILY DISABLED
//		}catch(BadRequest $e){
//			$this->dispatchRequest(array("c"=>"ErrorHandler","a"=>"pageNotFound"));
//		}catch(Exception $e){
//			$this->dispatchRequest(array("c"=>"ErrorHandler","a"=>"genericError"));
//		}
	}
}